package code.cando;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * author : yeswater
 * date : 2023/12/7
 * <p>
 * 组合总和
 */

public class T039 {
    public static void main(String[] args) {
        int[] arr = {7, 2, 6, 3};

        int target = 7;
        List<List<Integer>> lists = combinationSum(arr, target);
        System.out.println(lists.toString());
    }

    static List<List<Integer>> res = new ArrayList();
    static List<Integer> tmp = new ArrayList();
    static LinkedList<Integer> path = new LinkedList<>();

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        // func(candidates, target, 0, 0);
        Arrays.sort(candidates); // 这里sort 加上后面的 i = index 一起使用 达到去重效果
        func1(candidates, target, 0, 0);
        return res;
    }

    public static void func1(int[] candidates, int target, int sum, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(tmp));  // 这里一定要 new 否则引用会被继续使用 直到最后清空元素......
            return;
        }
        for (int i = index; i < candidates.length; i++) { // 这里 i = index 是为了结果去重
            if (sum + candidates[i] > target) {
                break;
            }
            tmp.add(candidates[i]);
            func1(candidates, target, sum + candidates[i], i);
            tmp.remove(tmp.size() - 1);
        }
    }

    public static void func(int[] candidates, int target, int sum, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(path)); // 这里一定要 new 否则引用会被继续使用 直到最后清空元素......
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (sum + candidates[i] > target) {
                break;
            }
            
            path.add(candidates[i]);
            func(candidates, target, sum + candidates[i], i);
            // 回溯的灵魂
            path.removeLast();
        }
    }
}
